var fs = require('fs');
let { minify } = require('terser')
var config = require('./config');
var exec = require('child_process').exec;
var {copyFile,fileReplace,copyFolder} = require('./tools/node');
var min = false,flag = 2;
if(process.argv[2] == '-min') {
	min = true;
	flag = 3;
}

 function customer_minify(s,unMinify){
	if(min && !unMinify) {
		// (async ()=>{
		// 	try{
		// 		const result = await minify(s, {
		// 			compress: true,
		// 			mangle: true
		// 		})
		// 		if(!result.error) s = result.code
		// 	}catch(e){
				
		// 	}
		// })()
	}
	return s
}

var modules = {
	tools:{
		Bdv:{
			dependencies:['Ajax','Base64','MD5']
		},
		Ajax:{
			dependencies:['Storage','string','Item','clone','zIndex','Base64'],
			md:'tools/Ajax.md'
		},
		clone:{
			md:'tools/clone.md'
		},
		merge:{
			md:'tools/merge.md'
		},
		date:{
			md:'tools/date.md'
		},
		string:{
			md:'tools/string.md'
		},
		guid:{
			md:'tools/guid.md'
		},
		SQLite:{
			md:'tools/SQLite.md',
			dependencies:['clone']
		},
		Storage:{
			md:'tools/Storage.md'
		},
		Promise:{
			dependencies:['Item'],
			md:'tools/Promise.md'
		},
		Verify:{
			md:'tools/Verify.md'
		},
		Indicator:{
			md:'tools/Indicator.md',
			dependencies:['Storage']
		},
		Vnode:{
			mdependencies:['zIndex']
		},
		List:{
			md:'tools/List.md',
			dependencies:['SQLite','merge']
		},
		Vue:{
			md:'tools/Vue.md',
			dependencies:['Vnode','clone','merge','zIndex']
		},
		Timer:{
			md:'tools/Timer.md',
			dependencies:['merge','Storage']
		},
		window:{
			md:'tools/window.md',
			// dependencies:['string','date','Vue','Promise','Item','Storage','Ajax','zIndex','setImgSize','clone']
			dependencies:['string','date','Vue','Item','Storage','Ajax','zIndex','setImgSize','clone']
		},
		$:{
			md:'tools/$.md',
			dependencies:['window']
		},
		H5:{
			md:'tools/H5.md',
			dependencies:['window']
		},
		Tencent:{
			dependencies:['node']
		},
		TCB:{
			dependencies:['Tencent','node']
		}
	}
}

var projects = {miniApp:[],nodemvc:[]};

var buildFuns = {
	nodemvc:function(config){
		var nodemvcTools = {
			string:true,
			node:true,
			date:true,
			guid:true,
			Storage:true,
			MD5:true,
			Base64:true,
			Item:true,
			Verify:true,
			clone:true,
			SQLite:true,
			toolVerify:true,
			merge:true,
			Vnode:true,
			node:true,
			snowflake:true
		}
		if(config.tools){
			for(var key in config.tools){
				nodemvcTools[key] = config.tools[key];
			}
		}
		//nodemvc tool
		copyFile('./config.js',config.output + '/source/tool.js',config.replace,function(s){
			return customer_minify('var a = {};\r' + fileReplace(makeTool(nodemvcTools),config.replace)  + '\rmodule.exports = a;');
		})
		//copyFile('./nodemvc/package.json',config.output + '/package.json');
		//copyFile('./nodemvc/pm2.json',config.output + '/pm2.json');
		copyFile('./nodemvc/main.js',config.output + '/main.js');
		copyFile('./nodemvc/build.js',config.output + '/build.js');
		copyFolder('./nodemvc/source',config.output + '/source',config.replace,function(s,from){
			return /\.js$/.test(from) ? customer_minify(s.toString()) : s;
		})
		copyFolder('./nodemvc/entity',config.output + '/entity',config.replace,function(s,from){
			return /\.js$/.test(from) ? customer_minify(s.toString()) : s;
		})
		copyFolder('./nodemvc/router',config.output + '/router',config.replace,function(s,from){
			return /\.js$/.test(from) ? customer_minify(s.toString()) : s;
		})
		copyFolder('./nodemvc/server',config.output + '/server',config.replace,function(s,from){
			return /\.js$/.test(from) ? customer_minify(s.toString()) : s;
		})
		console.log('发布nodemvc到 ' + config.output + ' 完成\r\n\r\n-----------------------------------------------------------');
	},
	miniApp:function(config){
		var WeChat_tool = {
			string:true,
			date:true,
			merge:true,
			guid:true,
			Ajax:true,
			List:true,
			Verify:true,
			date:true,
			zIndex:true
		}
		var H5_tool = {
			string:true,
			date:true,
			merge:true,
			guid:true,
			Ajax:true,
			List:true,
			Verify:true,
			window:true,
			H5:true,
			zIndex:true,
			Vue:true,
			$:true,
			Bdv:true
			// Promise:true
		}
		if(config.tools){
			for(var key in config.tools){
				WeChat_tool[key] = config.tools[key];
				H5_tool[key] = config.tools[key];
			}
		}
		var num = 0;
		if(config.options.WeChat){
			num ++;
			var toKey = config.options.WeChat == true ? 'WeChat' : config.options.WeChat;
			var to = config.output + '/' + toKey + '/utils/tool.js';
			copyFile('./config.js',to,function(s){
				s = 'var a = {};\r' + fileReplace(makeTool(WeChat_tool),config.replace) + '\rmodule.exports = a;';
				return customer_minify(s);
			})
		}
		if(config.options.Alipay){
			num ++;
			var toKey = config.options.Alipay == true ? 'Alipay' : config.options.Alipay;
			var to = config.output + '/' + toKey + '/utils/tool.js';
			copyFile('./config.js',to,function(s){
				s = 'var a = {};\r' + fileReplace(makeTool(WeChat_tool),config.replace) + '\rmodule.exports = a;';
				return customer_minify(s);
			})
		}
		if(config.options.H5){
			num ++;
			var toKey = config.options.H5 == true ? 'H5' : config.options.H5;
			var to = config.output + '/' + toKey + '/js/tool.js';
			var entryString = fs.readFileSync('./entrys/window.js', 'utf-8');
			copyFile('./config.js',to,function(s){
				s = entryString.replace('{{tools}}',fileReplace(makeTool(H5_tool),config.replace));
				return customer_minify(s);
			})
		}
		//创建build
		copyFile('./config.js',config.output + '/build.js',config.replace,function(s){
			s = fs.readFileSync('./entrys/miniAppBuilder.js', 'utf-8');
			s = s.replace('{{tools}}',makeTool({
				zIndex:true,
				Vnode:true,
				node:true
			}))
			var pathAlipay = config.options.Alipay == true ? 'Alipay' : config.options.Alipay;
			var pathWeChat = config.options.WeChat == true ? 'WeChat' : config.options.WeChat;
			var pathH5 = config.options.H5 == true ? 'H5' : config.options.H5;
			s = s.replace('WeChat/','./' + pathWeChat + '/').replace('Alipay/','./' + pathAlipay + '/').replace('H5/','./' + pathH5 + '/')
			return customer_minify(s);
		})
		var files = {
			default:num > 1 ? ['package.json','README.md'] : [],
			WeChat:[
				'common.wxss',
				'utils',
				'components',
				config.nodemvc ? 'pages' : 'pages/err',
				'images'
			],
			H5:['index.html','js/index.js','js/vue.js','css/style.css','components','pages'],
			Alipay:[
				'utils/index.js'
			]
		}
		for(var key in files){
			if(!config.options[key] && key != 'default') continue;
			var toKey = config.options[key] == true ? key : config.options[key];
			for(var i = 0; i < files[key].length; i ++){
				var from = './miniApp' + (key != 'default' ? '/' + key : '') + '/' + files[key][i];
				var to = config.output + (key != 'default' ? '/' + toKey : '') + '/' + files[key][i];
				if(/\.[^\/]+$/.test(from)){
					copyFile(from,to,config.replace,function(s){
						if(/\/Customer\//.test(from)) return;
						return customer_minify(s);
					});
				}else{
					copyFolder(from,to,config.replace,function(s,from,to){
						if(/\/Customer\//.test(from)) return;
						return /\.js$/.test(from) ? customer_minify(s.toString()) : s;
					});
				}
			}
		}
		require(config.output + '/build.js')('./miniApp/',config.output + '/',min,false,config);
		console.log('发布miniApp到 ' + config.output + ' 完成\r\n\r\n-----------------------------------------------------------');
	}
}

if(process.argv[2] == '-md'){
	var file = fs.readFileSync('config.md','utf-8');
	for(var k in modules) for(var _k in modules[k]) if(modules[k][_k].md) file += '\r\n\r\n-----------------------------------------------------------\r\n\r\n' + fs.readFileSync(modules[k][_k].md,'utf-8');
	fs.writeFile('./README.md', file,function(err){
		if(err) {
			console.log('\n文档更新失败:' + err);
		}else{
			console.log('\n文档更新成功!');
		}
	})
}else{
	
	if(process.argv.length > flag){
		for(var i = flag; i < process.argv.length; i ++) _do(process.argv[i]);
	}else{
		for(var k in config) _do(k);
	}
	setTimeout(function(){
		for(var key in projects) {
			if(projects[key].length > 0 && buildFuns[key]) {
				for(var i = 0; i < projects[key].length; i ++) {
					buildFuns[key](projects[key][i]);
				}
			}
		}
	},1000)
}

const assert = require('assert');
assert('asd');
function _do(k){
	if(config[k].type == 'move'){
		move(k);
	}else{
		build(k);
	}
}
//authorize 授权时限
function makeTool(options,key,authorize){
	key = key || 'tools';
	var ps = '',builded = {};
	for(var key_ in options){
		(function(_key){
			if(!builded[_key]){
				builded[_key] = true;
				if(modules[key] && modules[key][_key] && modules[key][_key].dependencies) {
					for(var j = 0; j < modules[key][_key].dependencies.length; j ++) {
						if(!builded[modules[key][_key].dependencies[j]]) arguments.callee(modules[key][_key].dependencies[j]);
					}
				}
				var file = '\r' + fs.readFileSync('./' + key + '/' + _key + '.js','utf-8');
				var v = options[_key];
				switch(typeof v){
					case 'string':
						file = file.replace(new RegExp('module.exports =|module.exports=','g'),v);
						break;
					case 'function':
						file = v.call(null,file,_key,key);
						break;
					case 'object':
						if(v instanceof Array){
							file = file.replace(/\r/gm,'gangr').replace(/\n/gm,'gangn');
							for(var i = 0; i < v.length; i ++) file = file.replace(new RegExp('\/\/' + v[i] + ' begin(.*)\/\/' + v[i] + ' end'),'');
							file = file.replace(/gangr/img,'\r').replace(/gangn/img,'\n');
						}
						break;
					default:
						file = file.replace(new RegExp('module.exports =|module.exports=','g'),'a.' + _key + ' =');
						break;
				}
				ps += file;
			}
		})(key_)
	}
	ps += '\na.Version = ' + JSON.stringify({createTime:new Date().getTime(),authorize: 1000 * 60 * 60 * 24 * authorize || 0}) + ';\n';
	return ps;
}

function build(k){
	var c = config[k];
	if(projects[c.entry]){
		c.name = k;
		projects[c.entry].push(c);
		return false;
	}
	var files = c.entry || '';
	files = /\.js$/.test(c.entry) ? fs.readFileSync(c.entry,'utf-8') : files;
	files = files.replace(new RegExp('{{tools}}','g'),makeTool(c.tools,'tools',c.authorize));
	if(c.replace) files = fileReplace(files,c.replace);
	fs.writeFile(c.output, customer_minify(files,c.unMinify),function(err){
		if(err) {
			console.log('\n发布失败:' + k + '\nerr:' + err);
		}else{
			console.log('\n发布成功:' + k);
		}
	})
}

function move(k){
	var c = config[k];
	function _move(from,to,replace){
		var file = fs.readFileSync(from,'utf-8');
		if(typeof replace == 'function') file = replace(file);
		fs.writeFile(to, customer_minify(file,c.unMinify),function(err){
			if(err) {
				console.log('\n移动失败:' + from + '到' + to + '\nerr:' + err);
			}
		})
	}
	c.options.forEach(function(entry){
		_move(entry.from,entry.to,entry.replace);
	})
}